package com.ruoyi.hire.service.impl;


import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.CompanyConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hire.domain.vo.ValidateSmsResultVo;
import com.ruoyi.hire.service.IHireCompanyLoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class HireCompanyLoginServiceImpl implements IHireCompanyLoginService {

    @Resource
    private RedisCache redisCache;

    /**
     * 用人单位校验验证码
     *
     * @param code        验证码
     * @param uuid        唯一标识
     * @return 验证码
     **/
    public Boolean validateCaptcha(String code, String uuid) {
        String verifyKey = CompanyConstants.COMPANY_CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();//告知验证码已过期
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
        return true;
    }


    /**
     * 生成短信验证码
     *
     * @param count
     * @return
     */
    public String generateTextMessageCode(int count) {
        return (Math.random() + "").substring(2, 2 + count);
    }


    /**
     * 用人单位校验短信验证码
     *
     * @param phoneNumber 用人单位联系方式
     * @param code        用人单位输入的短信验证码
     * @return
     */
    public ValidateSmsResultVo validateSms(String phoneNumber, String code) {
        String verifyKey = CompanyConstants.COMPANY_REGISTER_SMS_CODE_KEY + StringUtils.nvl(phoneNumber, "");
        String smsCode = redisCache.getCacheObject(verifyKey);
        ValidateSmsResultVo vo = new ValidateSmsResultVo();
        if (smsCode == null) {
            vo.setResult(false);
            vo.setMessage("短信验证码验证失败");
        }
        if (!code.equalsIgnoreCase(smsCode)) {
            vo.setResult(false);
            vo.setMessage("短信验证码验证失败");
        }
        vo.setResult(true);
        vo.setMessage("短信验证码验证成功");
        return vo;
    }
}
